import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir))

from command_parser.command_parser_container import CmdParserContainer
from utils.common_utils import *
from configure.compiler_configure import *
from command_parser.ranlib_parse.ranlib_command_generator import RanlibGenCommand
from command_parser.option_parser import *
from command_parser.ranlib_parse.ranlib_option_dict import *

class RanlibParser(CmdParserContainer):
    
    def __init__(self, command=[], context=None, compiler="", options=[],
                 cwd=""):
        self.command = command
        self.context = context
        self.compiler = compiler
        self.options = options
        self.cwd = os.getcwd()
        self.cmdgen = RanlibGenCommand(context=self.context, cwd=self.cwd)
        
    def parse_command(self):
        self.compiler = self.command[0]
        raw_options = self.command[1:]
        
        self.options = self.build_option(parse_at_option(raw_options))
        self.compiler = real_binary_path(self.compiler)
        
        return self.compiler, self.options
    
    @staticmethod
    def build_option(raw_options=[]):
        plugins = []
        options = []
        files = []
        i = 0

        while i < len(raw_options): 
            item = raw_options[i]
            if item == '--plugin':
                if i+1 < len(raw_options):
                    plugins.append(raw_options[i+1])
                    i += 1
            elif item[0] == '-':
                options.append(item)
            else:
                files.append(item)
            i += 1

        # split options
        options = ['-' + opt for opt in ''.join(options) if opt != '-']

        # tag attribute to all options,plugins and files
        tag_plugins = [Option('--plugin', [plugin], PREFIX_SPACE) for plugin in plugins]
        tag_options = [Option(opt, [], PREFIX_SIMPLE) for opt in options]

        tag_files = [Option('', [file], PREFIX_MATCH) for file in files]
        
        return tag_options + tag_files + tag_plugins
    
    
    def get_input_options(self):
        input_opts = [option for option in self.options if not option.option]
        return input_opts
    
    
    def get_output_options(self):
        output_opts = [option for option in self.options if not option.option]
        return output_opts
    
    def get_original_command(self):
        return self.cmdgen.generate_original_command(compiler=self.compiler, options=self.options)
    
    
    